package com.ergwang.controller.admin;

import com.ergwang.Model.Result;
import com.ergwang.Model.User;
import com.ergwang.service.admin.UserService;
import com.ergwang.service.admin.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Creat by ergWang
 * Date: 2020/5/30
 * Time: 09:02
 *
 * 功能：处理用户的账号操作请求
 */
@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        if ("allUser".equals(action)){
            allUser(request,response);
        }else if ("searchUser".equals(action)){
            searchUser(request,response);
        }else if ("deleteUser".equals(action)){
            deleteUser(request,response);
        }
    }

    /**
     * 根据Id删除选中的那个用户信息
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int delete = userService.deleteUser(id);
        if (delete != 0){
            response.getWriter().println(gson.toJson(Result.ok()));
        }else {
            response.getWriter().println(gson.toJson("删除失败！请重试"));
        }
    }

    /**
     * 根据输入值，模糊查询用户名
     * @param request
     * @param response
     */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 从请求中获取关键字
        String word = request.getParameter("word");
        // 将关键字传给service处理，返回一个匹配后的结果集合，List格式
        List<User> userList = userService.searchUser(word);
        // 将List格式的结果集转换为Json数据发给前端
        Result result = new Result();
        result.setCode(0);
        result.setData(userList);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 展示所有的用户信息列表
     * @param request
     * @param response
     */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.allUser();
        Result result = new Result();
        result.setCode(0);
        result.setData(userList);
        response.getWriter().println(gson.toJson(result));
    }
}
